// 系统登录界面
// pages/syslogin/syslogin.js
var session = require('../../common/session')
var account = require('../../common/account')
var config = require('../../common/config')
//获取应用实例
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    disabled: true,
    no: '',
    pwd: '',
    tenant: '',
    noinput: false,
    pwdinput: false,
    showView: false,
    optionBusiness: [
      { text: 'MOM', value: config.service.constMOM },
      // { text: 'WMS', value: config.service.constWMS },
      { text: 'HYMS', value: config.service.constHYMS }
    ],
    valueBusiness: config.service.constMOM
  },
  // 判断登录按钮是否可用
  setBtnOkIsDisable() {
    if (this.data.noinput && this.data.pwdinput) {
        this.setData({ disabled: false });
    }
    else
      this.setData({ disabled: true });
  },
  // 实时获取帐号信息
  noinput: function (e) {
    let val = e.detail.value;
    if(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val)){
      this.setData({
        no: val,
        noinput: val.length === 0 ? false : true
      });
      this.setBtnOkIsDisable();
    }
  },
  noblur: function (e) {
    let val = e.detail.value;
    if(!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val)){
      wx.showToast({
        title: '请正确填写您的手机号码！',
        icon: 'none',
        duration: 2000
      });
      this.setData({
        no: val,
        noinput: false
      });
      this.setBtnOkIsDisable();
    } else {
      this.setData({
        no: val,
        noinput: val.length === 0 ? false : true
      });
      this.setBtnOkIsDisable();
    }
  },
  // 实时获取密码
  pwdinput: function (e) {
    this.setData({
      pwd: e.detail.value,
      pwdinput: e.detail.value.length == 0 ? false : true
    });
    this.setBtnOkIsDisable();
  },
  pwdblur: function (e) {
    this.setData({
      pwd: e.detail.value,
      pwdinput: e.detail.value.length == 0 ? false : true
    });
    this.setBtnOkIsDisable();
  },
  // 系统切换
  businessChange: function (e) {
    this.setData({
      valueBusiness: e.detail
    })
   
      this.setBtnOkIsDisable();
      this.setData({
        isShowTenant: false
      })
    
  },
  // 微信自带获取微信用户信息
  getUserProfile: function (e) {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        wx.getSetting({
          success(result) {
            if (result.authSetting['scope.userInfo'])
              session.set("xyznzzwechatUserInfo", res.userInfo)
            that.btnSubmit();
          }
        })
      }, fail: (e)=>{
        that.setData({ disabled: false });
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    });
    session.set("xyznzzwechatUserInfo",  e.detail.userInfo)
    this.btnSubmit();
  },
  submitFun(){
    let that = this;
    wx.login({
      success (res) {
        if (res.code) {
          if (wx.getUserProfile) {
            that.getUserProfile();
          } else {
            that.getUserInfo();
          }
        
        } else {
          wx.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
    
  },
  // 登录
  btnSubmit() {
    var that = this;
    wx.showLoading({
      title: '登录中...',
    })
    that.setData({ disabled: true });
    wx.request({
      url: config.service.yrrmsHost + config.service.loginUrl,
      data: {
        UserNameOrEmailAddress: that.data.no,
        Password: that.data.pwd
      },
      method: 'POST',
      header: {
        // 'Abp.TenantId': session.get("Abp.TenantId"),
        'Content-Type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
         
          session.set('xyznzzaccessToken', res.data.result.accessToken);
          session.set('xyznzzbusiness', that.data.valueBusiness);
          let userName = res.data.result.userName;
          let userInfo = session.get("xyznzzwechatUserInfo");
          userInfo = userInfo instanceof Object?userInfo:{};
          userInfo.nickName = userName?userName:userInfo.nickName;
          session.set("xyznzzwechatUserInfo",userInfo);
          let curTime  = new Date().getTime();
          let sevenDay = 24 * 3600 * 7000;
          session.set("xyznzzwechatEffective",curTime + sevenDay);

          // 用户项目权限
          // let 
          // 用户项目权限 END

          wx.request({
            url: config.service.yrrmsHost + '/api/TokenAuth/SetUserOpenId',
            data: {
              userId: res.data.result.userId,
              openId: session.get('xyznzzopenId'),
              loginProvider: 'miniprogram'
            },
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded', // 默认值
              'Authorization': 'Bearer ' + session.get('xyznzzaccessToken')
            },
            success: function (res) {
            }
          })
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
            mask: true,
            success: function () {
              session.set("xyznzzIsNotFirst", false);
              setTimeout(function () {
                let identity = session.get('xyznzzwechatIdentity');
                if(identity){
                  wx.redirectTo({
                    url: '../operation/operation?identity='+identity
                  })
                } else {
                  wx.redirectTo({
                    url: '../identitySelection/identitySelection'
                  })
                }
                // wx.switchTab({
                //   url: '../dashboard/dashboard'
                // })
              }, 100)
            }
          })
        } else {
          that.setData({ disabled: false });
          session.set("xyznzzwechatUserInfo", '')
          var curMsg = "程序异常！";
          if(res.data.error){
            if(res.data.error.message == 'Nombre de usuario o contraseña incorrecta'){
              curMsg = "手机号或密码无效";
            } else {
              curMsg = "手机号或密码错误";
            }
          }

          wx.showToast({
            title: curMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (res) {
        that.setData({ disabled: false });     
        session.set("xyznzzwechatUserInfo", '')
        wx.showToast({
          title: '登录失败',
          icon: 'none',
          duration: 2000
        });
      },
      complete: function (res) {
      
      }
    })
  
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    wx.showLoading({
      title: '加载中...',
    });
    wx.showShareMenu({
      withShareTicket: true
    });
    this.autoUpdate(function(){
      getLoginStatus(_this);
    })
},
  onShow: function () {
    
  }, 
  onLaunch: function() {
    let _this = this;
    this.autoUpdate(function(){
      getLoginStatus(_this);
    })
  },
  autoUpdate: function(callback) {
    var self = this;
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function(res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //检测到新版本，需要更新，给出提示
          wx.hideLoading();
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本，是否下载新版本并重启小程序？',
            success: function(res) {
              if (res.confirm) {
                //2. 用户确定下载更新小程序，小程序下载及更新静默进行
                self.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                wx.showModal({
                  title: '温馨提示~',
                  content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                  showCancel:false,//隐藏取消按钮
                  confirmText:"确定更新",//只保留确定更新按钮
                  success: function(res) {
                    if (res.confirm) {
                      //下载新版本，并重新应用
                      self.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        } else {
          if(callback && callback instanceof Function){
            callback();
          }
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  }, 
   /**
  * 下载小程序新版本并重启应用
  */
 downLoadAndUpdate: function (updateManager){
   var self=this
   wx.showLoading();
   //静默下载更新小程序新版本
   updateManager.onUpdateReady(function () {
     wx.hideLoading()
     //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
     updateManager.applyUpdate()
   })
   updateManager.onUpdateFailed(function () {
     // 新的版本下载失败
     wx.showModal({
       title: '已经有新版本了哟~',
       content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
     })
   })
 }

})

function getLoginStatus(_this){
  wx.request({
    url: config.service.GetAllProcessingOrderDto,
    data: {
      StartDate: '',
      EndDate: '',
      OrderStatus: '',
      Sturt: 2,
      IsSupplier: true,
      Filter:'',
      MaxResultCount: 10,
      SkipCount:0
    },
    method: 'GET',
    header: {
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + session.get('xyznzzaccessToken')
    },
    success: function (res) {
     if(res.statusCode == '401'){
      session.allClear();}
    },complete:function(){
      let xyznzzwechatEffective = session.get("xyznzzwechatEffective");
      xyznzzwechatEffective = xyznzzwechatEffective ? xyznzzwechatEffective:0;
      // 判断当前时间，登录时效超过7天，清空缓存数据
      if(xyznzzwechatEffective <= new Date().getTime()) {
        session.allClear();
      }
      if(session.get("xyznzzwechatUserInfo")){
        let userInfo =session.get("xyznzzwechatUserInfo");
        let identity =session.get('xyznzzwechatIdentity');
        if(identity){
          wx.redirectTo({
            url: '../operation/operation?identity='+identity
          })
        } else {
          wx.redirectTo({
            url: '../identitySelection/identitySelection'
          })
        }
      } else {
        _this.setData({
          showView:true
        });
        if (wx.getUserProfile) {
          _this.setData({
            canIUseGetUserProfile: true
          })
        }
      }
      wx.hideLoading();
    }
  });

}